from django.core.cache import cache
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.

from django.db import models
from django.views import View

from apps.areas.models import Area


class AreaView(View):
    def get(self, request):
        province_list = cache.get('province_list')
        if not province_list:
            try:
                provinces = Area.objects.filter(parent=None)
                province_list = []
                for province in provinces:
                    province_list.append({'id': province.id, 'name': province.name})

            except Exception as e:
                print(e)
                return JsonResponse({'code': 400, 'errmsg': '查询失败'})
            cache.set('province_list', province_list, 3600 * 24)
        # else:
        #     print('使用缓存')
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': province_list})


# http://www.meiduo.site:8800/areas/210000/
class CityCountyView(View):
    def get(self, request, pid):
        sub_data = cache.get('sub_data_%s' % pid)
        if not sub_data:
            try:
                parent_obj = Area.objects.get(id=pid)
                sub_objs = parent_obj.subs.all()
                subs = []
                for sub in sub_objs:
                    subs.append({'id': sub.id, 'name': sub.name})
                sub_data = {'id': pid, 'name': parent_obj.name, 'subs': subs}
            except Exception as e:
                print(e)
                return JsonResponse({'code': 400, 'errmsg': '查询失败'})
            cache_key_name = 'sub_data_%s' % pid
            cache.set(cache_key_name, sub_data, 3600 * 24)
        # else:
        #     print('缓存数据')
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'sub_data': sub_data})
